<html>

<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>一张图系统功能-geojson</title>
  <meta name="keywords" content="规划一张图" />
  <meta name="description" content="一张图系统" />
  <link rel="stylesheet" href="./resource/ol/ol.css">
  <script src="./resource/ol/ol.js"></script>
</head>

<body>
  <!-- 地图容器 -->
  <div id="map" class="map"></div>

  <div id="popup" class="ol-popup" style="background-color:#fff;">
    <a href="#" id="popup-closer" class="ol-popup-closer"></a>
    <div id="popup-content"></div>
  </div>

  <script type="text/javascript">

    /** 创建要添加的图层**/
    // 创建图层：路网
    const LWLayer = new ol.layer.Tile({
      source: new ol.source.XYZ({
        // 设置本地离线瓦片所在路径
        url: 'mapabc/roadmap' + '/{z}/{x}/{y}.png',
      }),
      name: '路网地图',
    });

    // 创建图层：影像
    const YXMapLayer = new ol.layer.Tile({
      source: new ol.source.XYZ({
        // 设置本地离线瓦片所在路径
        url: 'mapabc/satellite' + '/{z}/{x}/{y}.jpg',
      }),
      name: '影像地图'
    });

    // 黑色的地图
    let TileLayer = new ol.layer.Tile({
      source: new ol.source.XYZ({
        url: "http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}"
      })
    });

    // 官网读取GeoJson的方法
    let vectorSource = new ol.source.Vector({
      url: 'geojson/ChinaFull.geojson',
      // url: 'http://localhost:8080/geoserver/ne/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=ne%3Adisputed_areas&maxFeatures=50&outputFormat=application%2Fjson',
      format: new ol.format.GeoJSON({featureProjection: 'EPSG:3857'}),
    });
    console.log(vectorSource);

    // 另一种读取geojson的方式
    // let json = fetch("http://localhost/geojson/ChinaFull.geojson")
    // .then((response) => {
    //   console.log(response);
    //   return response;
    // });
    // let vectorSource = (new ol.format.GeoJSON()).readFeatures(json);

    // 将geojson数据转化为ol要素
    fetch("geojson/ChinaFull.geojson")
      .then((res) => res.json())
        .then((data) => {
          var features = new ol.format.GeoJSON().readFeatures(data);
          console.log(features);
        });

    // 图层的样式
    var styles = new ol.style.Style({
      stroke: new ol.style.Stroke({
        color: 'blue',
        width: 2,
        opacity: 1
      }),
      fill: new ol.style.Fill({
        color: 'red',
        opacity: 0.5,
      }),
      text: new ol.style.Text({
        text: 'name',
        font: '12px bold serif',
        fill: new ol.style.Fill({
          color: '#000'
        }),
        stroke: new ol.style.Stroke({
          color: '#fff',
          width: 2
        })
      })
    });

    // geojons数据的图层
    let VectorLayer = new ol.layer.Vector({
      source: vectorSource,
      style: styles, // 图层样式
      zIndex: 2
    });

    /**** 创建地图视图 ****/
    let centerPos = ol.proj.transform([117.96, 36.64], 'EPSG:4326', 'EPSG:3857');
    let zoom = 5;
    var view = new ol.View({
      center: centerPos, //地图中心位置
      zoom: zoom, //地图初始层级
      maxZoom: 18,
      minZoom: 1
    });

    //创建地图,把地图挂接到容器上
    let map = new ol.Map({
      target: 'map',
      layers: [LWLayer, VectorLayer],
      view: view,
    });

    // 加载了geojson图层后，可以通过点击要查看的图层查看属性
    // var select = new ol.interaction.Select({
    //   condition: 'click',
    // });
    // map.addInteraction(select);
    // select.on("select", (e) => {
    //   console.log("e", e);
    // });

    /***** 添加单击响应函数来处理弹窗动作,查看图层属性 ****/
    map.on("click", function (e) {
      /* var feature = map.getFeaturesAtPixel(e.pixel);
      console.log(feature) */
      var pixel = map.getEventPixel(e.originalEvent);
      var hit = map.hasFeatureAtPixel(pixel);

      //获取到当前像素下的feature
      var feature = map.forEachFeatureAtPixel(pixel, function (feature, layer) {
        return feature;
      });
      console.log(feature)
      var coordinate = e.coordinate;
      content.innerHTML = "<p>你点击了这里:</p><code>" + feature.values_.name + "</code>"; // feature.get('name')
      overlayPop.setPosition(coordinate);
    });

    /**** 创建一个叠加层对象用作显示弹窗 ****/
    var container = document.getElementById("popup");
    var content = document.getElementById("popup-content");
    var closer = document.getElementById("popup-closer");

    var overlayPop = new ol.Overlay({
      element: container,
      autoPan: true,
      autoPanAnimation: {
        duration: 250
      }
    });

    map.addOverlay(overlayPop);

    // 为弹窗添加一个响应关闭的函数
    closer.onclick = function () {
      overlayPop.setPosition(undefined);
      closer.blur();
      return false;
    };

  </script>
</body>

</html>